package com.xt.base.wireless.server.http;


import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.xt.base.action.BaseAction;
import com.xt.base.exception.SystemError;
import com.xt.base.reflection.BaseReflector;
import com.xt.base.util.SpringUtil;
import com.xt.base.wireless.server.JsonUtil;
import com.xt.base.wireless.server.MobileActionUtil;
import com.xt.base.wireless.server.Xml2Json;

/**
 * <br>
 * <br>
 * 
 * <p>
 * <a href="HttpServerListener.java.html"><i>查看源文件</i></a>
 * </p>
 * 
 * @author 杨洪波
 * @create-date:2010-9-12
 */
public class HttpServerListener extends BaseAction{
	private static final long serialVersionUID = -3173083336345659206L;

	Logger log = Logger.getLogger(getClass());
	
	private String sendMsg;
	
	private String device;

	public String execute() {
		HttpServletRequest req = this.getRequest();
		Enumeration  names = req.getHeaderNames();
		while(names.hasMoreElements()){
		    String name = (String)names.nextElement();
		    System.out.println("<b>" + name + ":</b>" + req.getHeader(name) + "<br />");
		    System.out.println(name + ":" + req.getHeader(name) + "");
		}
		
		log.info("-----------已经进入HttpServerListener.execute,contentLength="+this.getRequest().getContentLength());
		String xml = this.getRequest().getParameter("paramXml");
		
		try {
			if(StringUtils.isEmpty(xml)){
				xml = this.getRequest().getHeader("paramXml");
				//xml = Base64.base64Decode(xml);
				//xml = new String(xml.getBytes("ISO-8859-1"));
				
				log.info("---getHeader,xml="+xml);
			}
			
			if(StringUtils.isEmpty(xml)){
				InputStream is = this.getRequest().getInputStream();
				int len=0,size=1024;
				byte[] bytes = new byte[size];
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				while((len=is.read(bytes,0, size))>0){
					baos.write(bytes, 0, len);
				}
				xml = new String(baos.toByteArray(),"UTF-8").trim();
				baos.close();
				baos = null;
				bytes=null;
			}
			
			if(StringUtils.isEmpty(xml)){
				InputStream is = this.getRequest().getInputStream();
				DataInputStream dis = new DataInputStream(is);
				xml = dis.readUTF();
			}
			
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		System.out.println("#$#$#$"+xml);
		log.info("-----------传入HttpServerListener.execte的参数xml= "+xml);
		
		if(StringUtils.isEmpty(xml)){
			sendMsg = "<exception>传入的参数为空</exception>";
			return "j2mepage";
		}
		
		Map<String,Object> map = MobileActionUtil.parseRequestXml(xml);
		if(map.get("action")==null){
			throw new SystemError(new Object(),new Object[]{xml},"没有指定Action！");
		}
		if(map.get("method")==null){
			throw new SystemError(new Object(),new Object[]{xml},"没有指定Method！");
		}
		
		device = map.get("device")==null?null:map.get("device").toString();
		
		Object o = null;
		try{
			o = SpringUtil.getWebBean(String.valueOf(map.get("action")));
		}catch(Exception e){
			e.printStackTrace();
			throw new SystemError(this,new Object[]{},"指定的Action不正确，或者没有为Spring配置Action！");
		}
		try{
			log.info("开始调用业务代码，获取数据");
			String methodName = String.valueOf(map.get("method"));
			map.remove("method");
			map.remove("action");
			//String tmpXml = MobileActionUtil.parseResultMap2Xml(map);
			o = BaseReflector.invoke(o, methodName, map, Map.class);
			log.info("调用业务代码结束，已取得数据，得到一个对像o="+o);
		}catch(Exception e){
			e.printStackTrace();
			throw new SystemError(this,new Object[]{},"指定的Method不正确，或者Method的参数类型不匹配！");
		}
		log.info("ffffffffffffffffffffffffffffffffffffffffffffffffff");
		if(o!=null){
			if(device!=null && device.indexOf("ios")>=0){
				sendMsg = JsonUtil.xml2Json(String.valueOf(o));
				//sendMsg = Xml2Json.ConvertXMLtoJSON(String.valueOf(o));
			}else{
				sendMsg = String.valueOf(o);
			}
		}
		/*if(o!=null && o instanceof Map<?,?>){//有具体返回值时，才需要解析为xml文件，并处理回调。
			map = (Map<String,Object>)o;
			log.info("MOA服务器端已响应手机端的请求，返回结果集");
		}else{
			map = new HashMap<String,Object>();
			map.put("baded", "yes");
			log.info("MOA服务器端已响应手机端的请求，返回服务器端异常标识。");
		}
		sendMsg = MobileActionUtil.parseResultMap2Xml(map);*/
		log.info(sendMsg);
		log.info("PC端MOA服务器HttpServerListener.execute执行结束...");
		return "j2mepage";
	}

	public String getSendMsg() {
		return sendMsg;
	}

	public void setSendMsg(String sendMsg) {
		this.sendMsg = sendMsg;
	}
	
	
}
